//
//  Service.m
//  alotOf
//
//  Created by Mac_Black_Mini on 2025/9/5.
//


#import "Service.h"
#import "VPNService.h"
#import "AdService.h"
#import <FirebaseRemoteConfig/FirebaseRemoteConfig.h>
#import "MJExtension/MJExtension.h"
#import "Config.h"

@implementation Service

static Service *instance;

+ (instancetype)shared {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[super allocWithZone:NULL] init];
        [instance initialize];
    });
    return instance;
}

- (void)initialize {
    // 初始化RemoteConfig（与原逻辑一致）
    FIRRemoteConfigSettings *settings = [[FIRRemoteConfigSettings alloc] init];
    settings.fetchTimeout = 15;
    FIRRemoteConfig.remoteConfig.configSettings = settings;
    
    // 初始化三个服务
    [[AdService shared] initializeAd];
    [[VPNService shared] connectState];
    
    // 监听App前台通知（广告唤醒）
    [NSNotificationCenter.defaultCenter addObserver:self
                                           selector:@selector(applicationWillEnterForeground)
                                               name:UIApplicationWillEnterForegroundNotification
                                             object:nil];
}

- (void)start {
    [self fetchRemoteConfig];
    // VPN服务无需主动启动，外部调用时触发
}

#pragma mark - RemoteConfig解析（数据分发）
- (void)fetchRemoteConfig {
    [FIRRemoteConfig.remoteConfig fetchWithExpirationDuration:0 completionHandler:^(FIRRemoteConfigFetchStatus status, NSError *error) {
        if (status == FIRRemoteConfigFetchStatusSuccess) {
            [FIRRemoteConfig.remoteConfig activateWithCompletion:^(BOOL changed, NSError * _Nullable error) {
                if (!error) [self handleRemoteConfig];
            }];
        }
    }];
}

- (void)handleRemoteConfig {
    // 1. 解析节点，传给VPN服务
    NSString *nodesStr = [[FIRRemoteConfig.remoteConfig configValueForKey:@"nodes"] stringValue];
    NSArray *nodeEncodeArray = [Tools stringToJson:nodesStr];
    NSMutableArray<Node *> *nodes = [NSMutableArray array];
    [nodeEncodeArray enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *decodeStr = [Tools decryptAES:obj key:@"VXH2THdPBsHEp+XZ" iv:@"VXH2THdPBsHEp+XZ"];
        [nodes addObject:[Node mj_objectWithKeyValues:decodeStr]];
    }];
    [[VPNService shared] setNodes:nodes];
    
    // 2. 解析广告配置，传给广告服务
    NSString *adKey = [NSString stringWithFormat:@"%@_v2_manage_advertising", [NSBundle.mainBundle objectForInfoDictionaryKey:@"AppTag"]];
    NSString *adConfig = [[FIRRemoteConfig.remoteConfig configValueForKey:adKey] stringValue];
//    [[AdService shared] setAdvertisingConfig:adConfig];
    
    // 3. 解析内购配置，传给内购服务
    NSString *configKey = [NSString stringWithFormat:@"%@_v2_manage_get_config", [NSBundle.mainBundle objectForInfoDictionaryKey:@"AppTag"]];
    NSString *configStr = [[FIRRemoteConfig.remoteConfig configValueForKey:configKey] stringValue];
    Config *config = [self decodeConfig:configStr];
//    [[IAPService shared] setConfig:config];
    
    // 4. 显示开屏广告
    [[AdService shared] showAdWithConfig:config.open_ad atViewController:Tools.window.rootViewController];
}

- (Config *)decodeConfig:(NSString *)configStr {
    // 配置解析逻辑（与原逻辑一致）
    NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:configStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSString *jsonStr = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
    jsonStr = [jsonStr substringWithRange:NSMakeRange(1, jsonStr.length - 2)];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\\" withString:@""];
    return [Config mj_objectWithKeyValues:jsonStr];
}

#pragma mark - 前台通知回调
- (void)applicationWillEnterForeground {
    // 刷新VIP状态
//    [[IAPService shared] refreshVIPStatus];
    // 同步VIP状态到广告服务（屏蔽广告）
//    [[AdService shared] setIsVip:[[IAPService shared] isVip]];
    // 显示唤醒广告
//    Config *config = [[IAPService shared] valueForKey:@"config"]; // 可优化为IAPService提供getConfig方法
    Config *config =[[AdService shared] valueForKey:@"config"];
    [[AdService shared] showAdWithConfig:config.wake_ad atViewController:Tools.window.rootViewController];
}

@end
